package dao

import (
	"context"
	"encoding/json"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

//-----支付配置

//支付配置列表
func (d *SiteSettingDao) PaySettingListDao(baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	var (
		lst    []paysetting.PaySetting
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Table("pay_setting")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, lst, count)
}

// 获取支付信息
func (d *SiteSettingDao) GetPaySettingInfoByAppid(appId string) *dingo.ErrorWrap {
	m := paysetting.New()
	db := global.Orm.Table("pay_setting").Where("app_id = ?", appId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// 获取支付信息
func (d *SiteSettingDao) GetPaySettingInfoByAppidAndMchid(appId, mchid string) *dingo.ErrorWrap {
	m := paysetting.New()
	db := global.Orm.Table("pay_setting").Where("app_id = ? and mch_id = ?", appId, mchid).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// 获取支付信息
func (d *SiteSettingDao) GetPaySettingInfoByTypeName(typeName string) *dingo.ErrorWrap {
	m := paysetting.New()
	db := global.Orm.Table("pay_setting").Where("type_name = ?", typeName).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

//支付配置编辑
func (d *SiteSettingDao) PaySettingEditDao(id int, m *paysetting.PaySetting) *dingo.ErrorWrap {

	db := global.Orm.Table("pay_setting")
	db.Where("id = ?", id)
	db.Model(&m)
	db.Updates(&m)
	if db.Error != nil {
		return dingo.ErrorIf(db.Error, false)
	}
	//更新redis中支付配置
	data, _ := json.Marshal(m)
	global.Rdb.Set(context.Background(), m.TypeName+"WeChatPayConfig", string(data), 0)

	return dingo.ErrorIf(db.Error, true)
}

//支付配置保存
func (d *SiteSettingDao) PaySettingSaveDao(param *paysetting.PaySetting) *dingo.ErrorWrap {

	db := global.Orm.Table("pay_setting")
	db.Create(&param)
	data, _ := json.Marshal(param)
	global.Rdb.Set(context.Background(), param.TypeName+"WeChatPayConfig", string(data), 0)

	return dingo.ErrorIf(db.Error, true)
}

//支付配置删除
func (d *SiteSettingDao) PaySettingDeleteDao(id int) *dingo.ErrorWrap {
	db := global.Orm.Exec("delete from pay_setting where id = ?", id)
	return dingo.ErrorIf(db.Error, true)
}
